package com.magictower.primary.engine;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;

import com.magictower.primary.bean.AppInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AppInfoParser {
    public static List<AppInfo> getAppInfos(Context context) {
        List<AppInfo> packegeAppInfos = new ArrayList<>();

        //获取包的管理者
        PackageManager packageManager = context.getPackageManager();
        //获取安装包
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);

        for (PackageInfo packageInfo : packageInfos) {
            AppInfo appInfo = new AppInfo();
            //获取应用程序图标
            Drawable icon = packageInfo.applicationInfo.loadIcon(packageManager);
            //获取应用程序名字
            String apkName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
            //获取应用程序包名
            String packageName = packageInfo.packageName;
            //获取apk路径，通过获取路径来获取程序大小
            String sourceDir = packageInfo.applicationInfo.sourceDir;
            File file = new File(sourceDir);
            long apkSize = file.length();
            //获取应用安装位置标记
            int flag = packageInfo.applicationInfo.flags;
            if ((flag & ApplicationInfo.FLAG_SYSTEM) != 0) {
                appInfo.setUserApp(false);//系统应用
            } else {
                appInfo.setUserApp(true);//用户应用
            }
            if ((flag & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
                appInfo.setRom(false);//SD卡
            } else {
                appInfo.setRom(true);//内存
            }

            appInfo.setIcon(icon);
            appInfo.setApkName(apkName);
            appInfo.setApkPackageName(packageName);
            appInfo.setApkSize(apkSize);

            packegeAppInfos.add(appInfo);
        }

        return packegeAppInfos;
    }
}
